package com.dunshan.data.config;

import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author liwen
 * @description: 数据源切换
 * @date 2021-08-15 12:46:32
 */
@Log4j2
@Aspect
@Component
public class DataSourceAspect {


    /**
     * 切点: 所有配置 DataSource 注解的方法
     */
    @Pointcut("execution(public * com.dunshan.data.controller..*.*(..))")
    public void controllerAspect() {
    }

    // 请求method前打印内容
    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取头标示
        String header = request.getHeader("dunshan");
        // 打印请求内容
        log.info("===============请求内容===============");
        log.info("请求地址:" + request.getRequestURL().toString());
        log.info("请求方式:" + request.getMethod());
        log.info("请求类方法:" + joinPoint.getSignature());
        log.info("请求类方法参数:" + Arrays.toString(joinPoint.getArgs()));
        log.info("请求类方法头信息:" + header);


        // 在请求url中判断
//        if (Arrays.toString(joinPoint.getArgs()).contains("master")) {
//            DynamicDataSource.setDataSource(DataSourceNames.MASTER);
//        } else {
//            DynamicDataSource.setDataSource(DataSourceNames.SLAVE);
//        }


        // 通过够信息判断
        if (header != null && header.equals("7dGgroup")) {
            DynamicDataSource.setDataSource(DataSourceNames.MASTER);
        } else {
            DynamicDataSource.setDataSource(DataSourceNames.SLAVE);
        }

    }
}
